package com.cndcare.msc.netty.controller;

import com.cndcare.msc.config.MyWebSocket;
import com.cndcare.msc.netty.bean.PcBean;
import com.cndcare.msc.netty.dao.jpa.PcBeanJpa;
import com.cndcare.msc.service.NettyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/pc")
public class PcController {

    @Autowired
    private PcBeanJpa pcBeanJpa;
    @Autowired
    private MyWebSocket myWebSocket;
    @Autowired
    private NettyService nettyService;

    @RequestMapping("/fillInfo/{mac}")
    public String fillInfo(
            Map<String, Object> map,
            @PathVariable("mac") String mac
    ) {
        PcBean pcBean = pcBeanJpa.findByMac(mac);
        map.put("pcBean", pcBean);
        map.put("statsDicMap", PcBean.statsDicMap);

        return "pc/fill_info";
    }

    @RequestMapping("/saveAndFlushPc")
    @ResponseBody
    public Map<String, Object> saveAndFlushPc(PcBean pcBean) {
        Map<String, Object> jsonMap = new HashMap<>();
        try {
            pcBean.setUpdateTime(new Date());
            nettyService.dealPcByMac(pcBean);
            pcBeanJpa.saveAndFlush(pcBean);

            myWebSocket.broadcastStatus();

            jsonMap.put("flag", true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonMap.put("flag", false);
            jsonMap.put("errorMsg", e.getMessage());
        }

        return jsonMap;
    }

}
